package com.tusuo.stds.ui.pay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mobileqq.openpay.api.IOpenApi;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.scenedetail.SceneDetailActivity_;
import com.tusuo.stds.ui.vip.VipActivity_;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.Map;

@EActivity(R.layout.activity_my_pay)
public class MyPayActivity extends BaseToolbarActivity<MyPayView,MyPayPresenter> implements MyPayView {

    @ViewById(R.id.pay_tv_pay_type)
    TextView tvType;
    @ViewById(R.id.pay_tv_scene_name)
    TextView tvTitle;
    @ViewById(R.id.pay_tv_price_top)
    TextView tvPriceTop;
    @ViewById(R.id.pay_tv_price_bottom)
    TextView tvPriceBottom;

    @ViewById(R.id.pay_rb_alipay)
    RadioButton rbAliPay;
    @ViewById(R.id.pay_rb_wechat)
    RadioButton rbWeChat;
    @ViewById(R.id.pay_rb_qq)
    RadioButton rbQQ;

    @ViewById(R.id.pay_layout_start_pay)
    LinearLayout layoutPay;
    @ViewById(R.id.pay_layout_ali_pay)
    RelativeLayout layoutAliPay;
    @ViewById(R.id.pay_layout_wechat_pay)
    RelativeLayout layoutWeChatPay;
    @ViewById(R.id.pay_layout_qq_pay)
    RelativeLayout layoutQQPay;
    @ViewById(R.id.pay_layout_scene_title)
    LinearLayout layoutScene;


    private String payType = ""; // 跳转到这个界面的方式,unlock是解锁场景,reward是打赏场景
    private String title = "";
    private float price;
    private int sceneId;
    private MyPayPresenter myPayPresenter;
    private int payTypeNo = 1;
    private String attachData;
    private Context mContext;
    private WXPayBroadcastReceiver receiver;
    private IOpenApi openApi;
    private SharedPreferences sp;
    private int lastChecked = 0;
    private String mVipMonth;
    private int mVipId;

    @NonNull
    @Override
    public MyPayPresenter createPresenter() {
        myPayPresenter = new MyPayPresenter(this);
        openApi = myPayPresenter.getOpenApi();
        return myPayPresenter;
    }

    @AfterInject
    public void init() {
        sp = getSharedPreferences("lastPay", Context.MODE_PRIVATE);
        lastChecked = sp.getInt("lastChecked", 0);

        mContext = MyPayActivity.this;
        Intent intent = getIntent();
        if (intent != null) {
            payType = intent.getStringExtra("payType");
            if ("vip".equals(payType)) {
                mVipMonth = intent.getStringExtra("vipMonth");
                mVipId = intent.getIntExtra("vipId", 0);
                price = (float) intent.getDoubleExtra("vipPrice",0);
            }else {
                title = intent.getStringExtra("sceneTitle");
                sceneId = intent.getIntExtra("sceneId", 0);
                if ("unlock".equals(payType)) {
                    price = intent.getFloatExtra("scenePrice",0);
                }else if ("reward".equals(payType)) {
                    price = (float) intent.getIntExtra("rewardMoney",0);
                }
            }

        }

        receiver = new WXPayBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.wxpay");
        registerReceiver(receiver,filter);
    }

    @AfterViews
    public void initData() {
        setupUI(this,getResources().getColor(R.color.white),getResources().getColor(R.color.black));
        ToolbarOwner.Config config = new ToolbarOwner.Config("确认订单", true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        if (!Utils.App.isQQAppInstalled(this)) {
            layoutQQPay.setVisibility(View.GONE);
        }

        if (!Utils.App.isWXAppInstalled(this)) {
            layoutWeChatPay.setVisibility(View.GONE);
        }


        if (!TextUtils.isEmpty(payType)) {
            if ("unlock".equals(payType)) {
                tvType.setText("开通场景");
                myPayPresenter.initData(sceneId,"unlock",0);
            }else if ("reward".equals(payType)) {
                tvType.setText("打赏场景");
                myPayPresenter.initData(sceneId,"reward",price);
            }else if ("vip".equals(payType)) {
                tvType.setText("开通会员");
                tvTitle.setText(mVipMonth);
                myPayPresenter.initData(mVipId,"vip",0);
            }
        }

        if (!TextUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }

        if (price != 0) {
            tvPriceTop.setText(price + "");
            tvPriceBottom.setText(price + "");
        }

        switch (lastChecked) {
            case 0: // 上次支付使用支付宝
                rbAliPay.setChecked(true);
                payTypeNo = 1;
                break;
            case 1: // 上次支付使用微信
                rbWeChat.setChecked(true);
                payTypeNo = 2;
                break;
            case 2: // 上次支付使用QQ
                rbQQ.setChecked(true);
                payTypeNo = 3;
                break;
        }
    }

    public void startPayAction() {
        if (TextUtils.isEmpty(attachData)) {
            return;
        }

        switch (payTypeNo) {
            case 0: // 没有选择支付方式
                Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                break;
            case 1: // 支付宝支付
                myPayPresenter.startPayAction(attachData,"AlipayForApp");
                break;
            case 2: //　微信支付
                myPayPresenter.startPayAction(attachData,"TenPayForApp");
                break;
            case 3:
                myPayPresenter.startPayAction(attachData,"QQPayForAndroidApp");
                break;
        }
    }

    @Override
    public void startPay(String attachData) {
        this.attachData = attachData;
    }

    @Override
    public void payByAliPay(final String credential) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(MyPayActivity.this);
                Map<String, String> payV2 = payTask.payV2(credential, true);
                String resultCode = payV2.get("resultStatus");
                Intent intent = new Intent("android.intent.action.wxpay");
                intent.putExtra("respCode",Integer.parseInt(resultCode));
                intent.putExtra("payByAlipay",true);
                sendBroadcast(intent);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Click({R.id.pay_rb_alipay, R.id.pay_layout_ali_pay})
    void clickAliPay() {
        payTypeNo = 1;
        lastChecked = 0;
        rbAliPay.setChecked(true);
        rbWeChat.setChecked(false);
        rbQQ.setChecked(false);
    }

    @Click({R.id.pay_rb_wechat, R.id.pay_layout_wechat_pay})
    void clickWechatPay() {
        payTypeNo = 2;
        lastChecked = 1;
        rbAliPay.setChecked(false);
        rbWeChat.setChecked(true);
        rbQQ.setChecked(false);
    }

    @Click({R.id.pay_rb_qq, R.id.pay_layout_qq_pay})
    void clickQqPay() {
        payTypeNo = 3;
        lastChecked = 2;
        rbAliPay.setChecked(false);
        rbWeChat.setChecked(false);
        rbQQ.setChecked(true);
    }

    @Click(R.id.pay_layout_start_pay)
    void clickPay() {
        Toast.makeText(mContext, "正在打开第三方支付", Toast.LENGTH_LONG).show();
        startPayAction();
        sp.edit().putInt("lastChecked",lastChecked).commit();
    }

    private class WXPayBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean payByAlipay = intent.getBooleanExtra("payByAlipay", false);
            int respCode = intent.getIntExtra("respCode", -1);
            String respMsg = "";

            if (!payByAlipay) {
                if (!TextUtils.isEmpty(intent.getStringExtra("respMsg"))) {
                    respMsg = intent.getStringExtra("respMsg");
                }

                if (respCode != 0 && respCode != -1 && respCode != -2) {
                    respCode = -1;
                }
            }

            switch (respCode) {
                case 9000:
                case 0:
                    // 支付成功
                    Toast.makeText(MyPayActivity.this, "支付成功" + respMsg, Toast.LENGTH_SHORT).show();

                    Intent intent1;

                    if ("unlock".equals(payType) || "reward".equals(payType)) {
                        intent1 = new Intent(MyPayActivity.this, SceneDetailActivity_.class);
                        intent1.putExtra("sceneId",sceneId);
                    } else {
                        intent1 = new Intent(MyPayActivity.this, VipActivity_.class);
                    }

                    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

                    startActivity(intent1);
                    finish();
                    break;
                case -1:
                    //　支付失败
                    Toast.makeText(MyPayActivity.this, "支付失败" + respMsg, Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    //　支付取消
                    Toast.makeText(MyPayActivity.this, "用户取消支付", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    //　支付失败
                    Toast.makeText(MyPayActivity.this, "支付失败" + respMsg, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

}
